package com.xzy.springboot.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/*此类为路由网关的一个全局过滤器(实现GlobalFilter, Ordered接口)*/
@Component
@Slf4j
public class LogFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
/*ServerWebExchange命名为服务网络交换机，存放着重要的请求-响应属性、请求实例和响应实例等等，有点像Context的角色。*/
        log.info("*******进入全局过滤器LogFilter:");
        //通过exchange可以获取此次请求的request和response;
        //获取request中uname参数
        String id = (String)exchange.getRequest().getQueryParams().getFirst("id");
        log.info("*********uname:" +id);

        if (id == "8"){
            log.info("*******参数异常");
            //出现异常则或取请求的response并设置code为错误(http状态码)
            exchange.getResponse().setStatusCode(HttpStatus.NOT_EXTENDED);
            //结束过滤器链
            return exchange.getResponse().setComplete();

        }


        //若无异常则将该exchange对象放入链中返回(即去执行下一个过滤器)
        return chain.filter(exchange);
    }

    /*此方法为设置该过滤器优先级*/
    @Override
    public int getOrder() {
        return 0;
    }
}
